package jvs.vfs.opt.browse;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import jvs.vfs.ContentTypes;
import jvs.vfs.IFile;
import jvs.vfs.opt.ItemInfo;
import jvs.vfs.opt.ItemListFileImpl;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.Browser;
import android.util.Log;

/**
 * 
 * @author qiangli
 * 
 */
public class BookmarkFileImpl extends ItemListFileImpl {

	private static final class FaveItem extends ItemInfo {
		long date;
		String url;
	}

	private static final String[] BOOKMARK_PROJ = new String[] {
			Browser.BookmarkColumns._ID, Browser.BookmarkColumns.URL,
			Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.BOOKMARK,
			Browser.BookmarkColumns.VISITS, Browser.BookmarkColumns.DATE,
			Browser.BookmarkColumns.FAVICON, };


	private static Bitmap folderIcon;

	private static final String[] LIST = { "/all", "/favorite", "/most",
		"/recent", };
	
	private static ItemInfo[][] lists = new ItemInfo[LIST.length][];

	private static final int LIST_ALL = 0; // history sort by title

	private static final int LIST_FAVES = 1;

	private static final int LIST_MOST = 2;

	private static final int LIST_RECENT = 3; // part of history sort by date

	private static final String LOG_TAG = "BookmarkFileImpl";

	private static final int MAX_COUNT = 32;

	private static final int MAX_TEXT_LEN = 80;

	static {
		try {
			InputStream is = BookmarkFileImpl.class
					.getResourceAsStream("/jvs/vfs/opt/browse/bookmark.png");
			folderIcon = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void load(Cursor c, ArrayList<ItemInfo> list, int max) {
		if (DEBUG) {
			Log.d(LOG_TAG, "load cursor: " + c);
		}
		if (c == null) {
			return;
		}

		try {
			if (!c.moveToFirst()) {
				return;
			}

			int colId = c.getColumnIndex(Browser.BookmarkColumns._ID);
			int colTitle = c.getColumnIndex(Browser.BookmarkColumns.TITLE);
			int colUrl = c.getColumnIndex(Browser.BookmarkColumns.URL);
			int colIcon = c.getColumnIndex(Browser.BookmarkColumns.FAVICON);
			int colDate = c.getColumnIndex(Browser.BookmarkColumns.DATE);

			int count = 0;
			long key = System.currentTimeMillis();

			do {
				FaveItem fi = new FaveItem();

				String id = c.getString(colId);
				fi.id = (id);

				String u = c.getString(colUrl);
				fi.url = (u);

				String t = c.getString(colTitle);
				if (t != null && t.length() > MAX_TEXT_LEN) {
					t = t.substring(0, MAX_TEXT_LEN);
				}
				fi.title = (t == null ? u : t);
				fi.date = c.getLong(colDate);
				byte[] data = c.getBlob(colIcon);
				if (data != null) {
					fi.icon = BitmapFactory.decodeByteArray(data, 0,
							data.length);
				} else {
					fi.icon = (null);
				}
				if (DEBUG) {
					Log.d(LOG_TAG, "title: " + t + " url: " + u);
				}

				key++;
				fi.sortkey = key + "";
				list.add(fi);
				count++;
				if (count > max) {
					break;
				}
			} while (c.moveToNext());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			c.close();
		}
	}

	private static ItemInfo[] loadAll() {
		ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
		//
		Context ctx = (Context) fs.getContext();
		ContentResolver cr = ctx.getContentResolver();
		String by = Browser.BookmarkColumns.TITLE + " ASC";
		Cursor c = cr.query(Browser.BOOKMARKS_URI, BOOKMARK_PROJ, null, null,
				by);
		load(c, list, Integer.MAX_VALUE);
		return list.toArray(new ItemInfo[0]);
	}

	private static ItemInfo[] loadFaves() {
		ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
		Context ctx = (Context) fs.getContext();
		ContentResolver cr = ctx.getContentResolver();
		String by = Browser.BookmarkColumns.TITLE + " ASC";
		Cursor c = cr.query(Browser.BOOKMARKS_URI, BOOKMARK_PROJ,
				"bookmark = 1", null, by);
		load(c, list, Integer.MAX_VALUE);
		return list.toArray(new ItemInfo[0]);
	}

	private static ItemInfo[] loadMost() {
		ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
		//
		Context ctx = (Context) fs.getContext();
		String sel = Browser.BookmarkColumns.VISITS + " != 0";
		String by = Browser.BookmarkColumns.VISITS + " DESC";
		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr
				.query(Browser.BOOKMARKS_URI, BOOKMARK_PROJ, sel, null, by);
		load(c, list, MAX_COUNT);
		return list.toArray(new ItemInfo[0]);
	}

	private static ItemInfo[] loadRecent() {
		ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
		//
		Context ctx = (Context) fs.getContext();
		String by = Browser.BookmarkColumns.DATE + " DESC";
		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr.query(Browser.BOOKMARKS_URI, BOOKMARK_PROJ, null, null,
				by);
		load(c, list, MAX_COUNT);
		return list.toArray(new ItemInfo[0]);
	}

	/**
	 * @param uri
	 */
	public BookmarkFileImpl(URI uri) {
		super(uri);
	}

	public BookmarkFileImpl(URI pu, ItemInfo ai) {
		super(pu, ai);
	}

	@Override
	public boolean execute() {
		try {
			final FaveItem item = (FaveItem) info;
			if (item == null) {
				return false;
			}
			Context ctx = (Context) fs.getContext();
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.parse(item.url), ContentTypes.TEXT_HTML);
			String ti = item.title;
			Intent ci = Intent.createChooser(i, ti);
			ci.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			ctx.startActivity(ci);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public String getContentType() {
		if (!isFolder) {
			return ContentTypes.APP_URI;
		}
		return ContentTypes.APP_FOLDER;
	}

	protected String[] getFolders() {
		return LIST;
	}

	@Override
	public Object getIcon() {
		if (isFolder) {
			if (isTop()) {
				return null;
			}
			return folderIcon;
		}
		final FaveItem item = (FaveItem) info;
		if (item != null) {
			return item.icon;
		}
		return null;
	}

	@Override
	public long getLastModified() {
		final FaveItem item = (FaveItem) info;
		if (!isFolder && item != null) {
			return item.date;
		}
		return super.getLastModified();
	}

	@Override
	public URI toRealURI() {
		final FaveItem item = (FaveItem) info;
		if (!isFolder && item != null) {
			try {
				return new URI(item.url);
			} catch (URISyntaxException e) {
				return null;
			}
		}
		return super.toRealURI();
	}

	protected ItemInfo[] load(Context ctx, int idx) {
		ItemInfo[] list = null;
		switch (idx) {
		case LIST_ALL:
			list = loadAll();
			break;
		case LIST_FAVES:
			list = loadFaves();
			break;
		case LIST_MOST:
			list = loadMost();
			break;
		case LIST_RECENT:
			list = loadRecent();
			break;
		}
		if (DEBUG) {
			Log.d(LOG_TAG, "loaded: " + idx + " : " + list);
		}
		return list;
	}

	@Override
	protected IFile newInstance(URI pu, ItemInfo ai) {
		return new BookmarkFileImpl(pu, ai);
	}

	@Override
	protected ItemInfo[][] lists() {
		return lists;
	}

}
